import Vue from 'vue'
import Vuex from 'vuex'
import { url } from "@/apiUrl"
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userMsg:{},//存放用户信息
    musics: [],//存放所有歌曲
    song:{
      title: "让生活充满音乐",
      author: "轻听音乐",
      url: `${url}/musics/music_1918576268.mp3`,
      pic: `${url}/images/image_1405283464.jpg`,
      lrc: "[00:00.00]作词： P.S.Y.潘紫棋\n[00:01.00] 作曲 : P.S.Y.潘紫棋\n",
    },//存放当前播放的单曲
    musicList: [],//存放主页推荐歌单
    List: [],//格式化所有播放数据,
    Play: [],//播放列表
    likeMusic: [],//用户喜欢的音乐
    collectAblum: [],//用户收藏的专辑
    collectPL_ids: [],
    collectPLs: [],//存放用户收藏的歌单
    createPL: [],//存放用户创建的歌单列表
    PlayHistory: [],//存放用户播放歌曲记录
    index: 0,
    isOn:false,
    start: true,//是否显示播放按钮的标志
    createList: false,//是否显示创建歌单对话框的标识
    search:[0,1,2,3,4],//存放所有搜索结果
    defdefaultActive:'1',
    currentTabComponent:null
  },
  getters: {
  },
  mutations: {
    getUsermsg(state,data){
      state.userMsg=data
      state.userMsg.avatar_url=`${url}/${state.userMsg.avatar_url}`
    },
    getMusics(state, musics) {//获取所有歌曲
      console.log(musics[0]);
      state.musics = musics;
    },
    getList(state, musics) {//格式化所有的歌曲
      for (var i in musics) {
        state.List[i] = {
          title: musics[i].music_name,
          author: musics[i].singer_name[0],
          url: `${url}/${musics[i].audio_url}`,
          pic: `${url}/${musics[i].img_url}`,
          lrc: musics[i].lyric,
          album: musics[i].album_name
        }
      }
    },
    getLikeMusic(state, payload) {//获取用户喜欢的音乐的
      axios
        .post(`${url}/users/getUserData`, {
          t: localStorage["qtUser"]
        })
        .then((res) => {
          state.likeMusic = []//每次重新请求时清空本地喜欢的音乐
          if (typeof res.data.data.LikeMusic != "undefined") {
            var musics = res.data.data.LikeMusic
            for (var i in musics) {
              musics[i] = {
                url: `${url}/${musics[i].audio_url}`,
              }
            }
            console.log(typeof res.data.data.LikeMusic);
            for (let url of musics) {
              for (let item of state.List) {
                if (item.url == url.url) {
                  state.likeMusic.push(item)
                }
              }
            }
            // state.likeMusic = [...new Set(state.likeMusic)]
            state.likeMusic = state.likeMusic.reverse()
            //数据更新完毕，调用回调函数更新歌曲小红心状态
            let [callback] = payload
            callback()
            console.log("更新后的likeMusic", state.likeMusic);
          } else {
            delete localStorage["qtuser"]
          }
        }).catch(() => { });
    },
    getCreatePL(state) {//获取用户创建的歌单
      axios.post(`${url}/users/getUserData`, {
        t: localStorage["qtUser"]
      })
        .then((res) => {
          console.log(res.data.data);
          state.createPL = res.data.data.CreatePL;
          console.log(state.createPL[0]);
        }).catch(() => { });

    },
    getCollect(state,callback) {//获取用户收藏的专辑
      axios.post(`${url}/users/getUserData`, {
        t: localStorage["qtUser"]
      })
        .then( res => {
          if (typeof res.data.data.CollectAblum != "undefined") {
                        state.collectAblum = res.data.data.CollectAblum
            callback()
          }else{
            state.collectAblum=[]
            callback()
          }
        }).catch(() => { })
    },
    getmusicList(state, musicList) {//获取主页歌单
      console.log("主页歌单：", musicList);
      state.musicList = musicList
      var arr2=[]
        for(let i=0,j=5;i<musicList.length;i=j,j+=5){
          arr2[j/5-1]=musicList.slice(i,j)
        } 
        state.musicList=arr2
    },
    handleAdd(state, payload) {//收藏音乐或歌单
      var { value, fieldName, callback } = payload
      for (let song of state.musics) {
        if (`${url}/${song.audio_url}` == value.url) {
          axios.post(`${url}/users/handleAdd`, {
            user_id: localStorage["qtUserId"],
            value: song.music_id,
            fieldName: fieldName
          },
            {
              headers: {
                'Authorization': localStorage["qtUser"]
              }
            }
          ).then(res => {
            callback()
          })
          break
        }
      }

    },
    pushCollectList(state, payload) {//收藏歌单
      let [playlist_id, callback] = payload
      axios.post(`${url}/users/handleAdd`, {
        user_id: localStorage[`qtUserId`],
        value: playlist_id,
        fieldName: `playlist_id`
      }, {
        headers: {
          'Authorization': localStorage["qtUser"]
        }
      })
        .then(res => {
          if (res.status == 200) {
            console.log(res.code);
            state.collectPL_ids.push(playlist_id)
            callback()
          }
        })
    },
    cancelCollectList(state, palyload) {
      let [id, callback] = palyload;
      let ids = state.collectPL_ids
      for (let i in ids) {
        if (ids[i] == id) {
          state.collectPL_ids.splice(i, 1)
        }
      }
      callback()
    },
    handleDel(state, payload) {//取消收藏音乐或歌单
      var { fieldValue, fieldName, callback } = payload
      for (let song of state.musics) {
        if (`${url}/${song.audio_url}` == fieldValue.url) {
          axios.post(`${url}/users/handleDel`, {
            user_id: localStorage["qtUserId"],
            fieldValue: song.music_id,
            fieldName: fieldName
          },
            {
              headers: {
                'Authorization': localStorage["qtUser"]
              }
            }
          ).then(res => { callback() })
          break
        }
      }
    },
    cancelCollect(state, payload){//取消收藏专辑
      var { fieldValue, fieldName, callback } = payload
          axios.post(`${url}/users/handleDel`, {
            user_id: localStorage["qtUserId"],
            fieldValue: fieldValue.album_id,
            fieldName: fieldName
          },
            {
              headers: {
                'Authorization': localStorage["qtUser"]
              }
            }
          ).then(res => {             
            callback()
           })        
    },
    CollectAlbum(state,payload){//收藏专辑
      var { album,callback } = payload
      console.log("当前专辑对象",this.album);
      axios.post(`${url}/users/handleAdd`, {
        user_id: localStorage[`qtUserId`],
        value: album.album_id,
        fieldName: `album_id`
      }, {
        headers: {
          'Authorization': localStorage["qtUser"]
        }
      })
        .then(res => {
          if (res.status == 200) {
            state.collectAblum.push(album)
            callback()
          }
        })
    },
    getSong(state, song) {//播放新歌曲
      state.isOn = true
      state.start = false
      state.song = song;
      for (let item of state.musics) {
        if (`${url}/${item.audio_url}` == song.url) {
          axios.post(`${url}/users/addPlayHistory`, {
            user_id: localStorage[`qtUserId`],
            music_id: item.music_id
          }, {
            headers: {
              Authorization: localStorage[`qtUser`]
            }
          }).catch(() => { })
        }
      }
      console.log("state中的单曲为：", state.song);
    },
    pushNewList(state, songList) {//播放某个歌单全部歌曲
      state.Play = songList
      console.log(state.Play);
    },
    playMusic(state) {//播放歌曲
      if (state.song.title != "让生活充满音乐") {
        state.isOn = true
        state.start = false
      }
    },
    pause(state) {//暂停歌曲
      console.log("state中的暂停");
      state.isOn = false
      state.start = true
    },
    pushSong(state, newMusic) {//添加歌曲到播放列表
      try {
        for (var i in state.Play) {
          if (state.Play[i].url == newMusic.url) {
            console.log("歌曲重复");
            state.Play.splice(i, 1)
            break
          }
        }
      } catch (e) { console.log(e) }
      state.Play.push(newMusic)
      console.log("播放歌单", state.Play)
    },
    deleteSong(state, Song) {//删除播放列表的歌曲
      let newPlay = state.Play.filter((this_song) => {//使用filter方法删除当前歌曲
        return this_song.url != Song.url
      })
      state.Play = newPlay;//更新播放列表
    },
    play(state, flag) {//在点击组件时控制播放图标和暂停图标
      if (flag) {
        console.log("播放按钮隐藏");
        state.start = false
      } else {
        console.log("暂停按钮隐藏");
        state.start = true
      }
    },
    createList(state, flag, flag1) {//控制创建歌单对话框
      state.createList = flag;
    },
    isLike(state, payload) {//查找当前music是否在likeMusic内
      let [music, callback] = payload;
      for (let song of state.likeMusic){//查找当前music是否在likeMusic内
        if (song.url == music.url) {
          callback(true)//存在则显示小红心
          break
        } else {
          callback(false)//循环结束都未找到则不显示红心
        }
      }
    },
    isCollect(state,payload){//查找当前album是否在collectAblum内
      var {url,callback}=payload;
      for(let i in state.collectAblum){
        console.log("配对值",url);
        console.log(state.collectAblum[i].album_pic);
        if(url==state.collectAblum[i].album_pic){
          callback(true)
          return
        }
      }
      callback(false)
    },
    getCollectAblum(){
      handleDel
    },
    getCollectPLs(state, list) {//获取所有的歌单id
      for (let item of list) {
        state.collectPL_ids.push(item.playlist_id)
      }
      console.log(state.collectPL_ids);
    },
    getCollectPL(state) {
      axios.post(`${url}/users/getUserData`, { t: localStorage.getItem("qtUser") }).then((res) => {
        state.collectPLs = res.data.data.CollectPL
        console.log(state.collectPLs);
      }).catch(err => { console.log(err.message) })
    },
  async  getPlayHistory(state, data) {//获取历史播放歌曲
      state.PlayHistory = []
        for (let item of data) {
      await axios.get(`${url}/musics/musicById?music_id=${item.music_id}`).then(res => {
          for (let song of state.List) { 
            try{           
            if (song.url == `${url}/${res.data.data[0].audio_url}`) {
              state.PlayHistory.unshift(song)
            }              
            }catch(error){
              console.log("找不到该歌曲，id是：",item.music_id);
            }
          }
        })   
      }             
    },
    getSearch(state,payload){//获取相关搜索内容
      let [number,keyword,callback]=payload;
        axios.get(`${url}/search?type=${number}&keyword=${keyword}`, {
          headers:{
            'Authorization': localStorage["qtUser"]
          }
        })
          .then(res=>{
            callback(res.data.data)
          })  
    },
    updateActive(state,key){
      state.defdefaultActive=key
    },
    updatecurrent(state,current){
      state.currentTabComponent=current
    },
    addTolist(state,payload){
      var [listId,value,callback]=payload
      for (let song of state.musics) {
        if (`${url}/${song.audio_url}` == value.url) {
          axios.post(`${url}/users/addMToCreatePL`, {
            createPL_id: listId,
            music_id: song.music_id,
          },
            {
              headers: {
                'Authorization': localStorage["qtUser"]
              }
            }
          ).then(res => {
            callback()
          })
          return
        }
      }
    },
    drop(state){
      state.createPL=[]
      state.collectPLs=[]
    }
  },
  actions: {
  },
  modules: {
  }
})
